from __future__ import absolute_import
import logging

logger = logging.getLogger('forest.plugins')
logger.setLevel(logging.INFO)

class PluginRegistry(object):
    def __init__(self):
        # TODO: ordered?
        self.plugins = {}
        
    def get(self, name):
        return self.plugins[name]
        
    def iteritems(self):
        return self.plugins.iteritems()
        
    def __iter__(self):
        return iter(self.plugins)

    def register(self, name, cls):
        logger.debug('Registering %s to %s' % (name, repr(cls)))
        self.plugins[name] = cls
            
            
registry = PluginRegistry()

class PluginMeta(type):
    """Metaclass for adding a plugin to the registry"""
    def __init__(cls, name, bases, dic):
        super(PluginMeta, cls).__init__(name, bases, dic)
        
        if cls is PluginMeta:
            return
        
        register_name = dic.get('__register__')
        if not register_name:
            raise Exception("Could not find declared __register__ property on Stage class %s" % cls.__name__)
            
        registry.register(register_name, cls)
        
import pkgutil    

from os.path import dirname, join
def search_plugins(path, prefix):
    logger.debug('Searching for plugins under %s...', path)
    paths = [path]
    
    for importer, modname, ispkg in pkgutil.walk_packages(path=paths, prefix=prefix, onerror=lambda x: None):
        module = __import__(modname, fromlist="dummy")
        logger.debug('Imported module %s.', module)
    
    return registry
    #for importer, name, ispkg in pkgutil.iter_modules(stagepaths):
    #    print dir(importer)
    #    for module in importer.iter_modules(prefix=name):
    #        print module
        #for name, ispkg in importer.iter_modules(prefix=mod.__name__ + ".") :
        #    if ispkg :
